<?php

namespace plugin\admin\app\controller;

use support\Request;
use support\Response;
use plugin\admin\app\model\QualityInfo;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 水质指标2 
 */
class QualityInfoController extends Crud
{
    
    /**
     * @var QualityInfo
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new QualityInfo;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('quality-info/index');
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);

        // 适配设备编号和网关ID筛选
        $deviceSn = $request->get('device_sn');
        $gatewayId = $request->get('gateway_id');
        if ($deviceSn || $gatewayId) {
            $query = $query->join('wa_devices as d', 'd.id', '=', 'wa_quality_info.device_id');
            if ($deviceSn) {
                $query = $query->where('d.sn', $deviceSn);
            }
            if ($gatewayId) {
                $query = $query->where('d.gateway_id', $gatewayId);
            }
            // 需要 select wa_quality_info.* 保证主表字段完整
            $query = $query->select('wa_quality_info.*');
        }

        $query = $query->with(['device' => function($q){
            $q->select('id', 'name','sn','status','auto','alarm','gateway_id');
        }]);

        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('quality-info/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('quality-info/update');
    }

}
